package com.coastline.fruit.usercenter.service.ansy;

import com.coastline.fruit.common.thread.CoastlineDefaultThreadFactory;
import com.coastline.fruit.common.thread.CoastlineThreadPoolManager;
import com.coastline.fruit.usercenter.entity.dao.UserDao;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author Coastline
 * @date 2025/1/25 22:29
 */
@Slf4j
public class UserThreadPool {
    private int maxPoolSize = 10;

    private int corePoolSize = 5;

    private int queueSize = 100;

    private int keepAliveTime = 60;

    private ThreadPoolExecutor threadPoolExecutor;

    private RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

    private static final UserThreadPool USERTHREADPOOL = new UserThreadPool();

    /**
     * 获取单例对象
     *
     * @return
     */
    public static UserThreadPool getInstance() {
        return USERTHREADPOOL;
    }

    public ThreadPoolExecutor getExecutor() {
        return threadPoolExecutor;
    }

    /**
     * new ArrayBlockingQueue<>(queueSize)
     */
    public void init() {
        threadPoolExecutor = CoastlineThreadPoolManager.createThreadPool("UserThreadPool",
                corePoolSize, maxPoolSize, keepAliveTime, new LinkedBlockingDeque<>(),
                new CoastlineDefaultThreadFactory("UserThreadPool-"), handler);
    }

    public void close() {
        if (threadPoolExecutor != null) {
            threadPoolExecutor.shutdown();
        }
    }

    public void execute(UserDao userDao) {
        if (threadPoolExecutor.getActiveCount() >= maxPoolSize) {
            log.warn("the thread pool full");
        }
        UserThread userThread = new UserThread(userDao);

        try {
            threadPoolExecutor.execute(userThread);
        } catch (RejectedExecutionException e) {
            log.error("failed to execute the task", e);
        }
    }


}
